package com.subsequent.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.subsequent.dto.UserDto;
import com.subsequent.method.LoginStrategy;
import com.subsequent.method.LoginStrategyFactory;
import com.subsequent.pojo.Users;
import com.subsequent.service.UsersService;
import com.subsequent.mapper.UsersMapper;
import com.subsequent.utils.BCrypt;
import com.subsequent.utils.MD5Utils;
import com.subsequent.utils.Result;
import com.subsequent.utils.ValidateCodeUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
* @author 申其卓
* @description 针对表【users(系统用户表)】的数据库操作Service实现
* @createDate 2025-05-06 15:56:58
*/
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users>
    implements UsersService{
    @Resource
    private LoginStrategyFactory loginStrategyFactory;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private UsersMapper usersMapper;
    @Override
    public Result login(UserDto dto) {
        LoginStrategy password = loginStrategyFactory.getStrategy("password");
        return password.login(dto);
    }

    @Override
    public Result loginCode(UserDto dto) {
        LoginStrategy code = loginStrategyFactory.getStrategy("code");
        return code.login(dto);
    }

    @Override
    public Result getCode() {
        Integer validateCode = ValidateCodeUtils.generateValidateCode(4);
        String key="UserCode1:";
        redisTemplate.opsForValue().set(key, validateCode,1,TimeUnit.MINUTES);
        return Result.success("验证码发送成功");
    }

    @Override
    public Result UpdatePassword(UserDto dto) {
        if(dto==null){
            return Result.error("参数错误");
        }
        QueryWrapper<Users>queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(Users::getPhone,dto.getPhone());
        Users users=usersMapper.selectOne(queryWrapper);
        if(users!=null){
            Integer userCode = (Integer) redisTemplate.opsForValue().get("UserCode1:");
            if(userCode.equals(dto.getCode())){
                String password = dto.getPassword();
                String hashpw = BCrypt.hashpw(password, BCrypt.gensalt());
                users.setPassword(hashpw);
                usersMapper.updateById(users);
                return Result.success("密码修改成功");
            }
            return Result.error("验证码错误");
        }
        return Result.error("手机号不存在");
    }
}




